#include "BondDict.h"
#include <fstream>

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
//#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// class CBondDict

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CBondDict::CBondDict()
{
}

CBondDict::~CBondDict()
{
	Clear( );
}

bool CBondDict::Add(BondDict &dict){
	std::string sgroup = dict.group_name;
	if (sgroup.length() <= 0)return false;
	std::lock_guard<std::mutex> locker(m_mutex);
	CBondList *parr=NULL;
	parr=GetBondArrByGroup(sgroup,true);
	if (!parr)return false;
	std::string skey = sgroup + "." + std::string(dict.selective_code);
	parr->m_list.insert(std::pair<std::string,BondDict>(skey,dict));
	return true;
}

int CBondDict::GetSize(){
	int res = 0;
	for (std::map<std::string, CBondList*>::iterator it = m_map.begin(); it != m_map.end(); ++it)
	{
		res += (int)it->second->m_list.size();
	}
	return res;
}

CBondDict& CBondDict::instance()
{
	static CBondDict s_bd;
	return s_bd;
}

CBondList * CBondDict::GetBondArrByGroup(const std::string &sGroup, bool bInsert)
{
	CBondList *parr = NULL;
	std::map<std::string, CBondList*> ::iterator itr = m_map.find(sGroup);
	if(itr!=m_map.end())
		parr = itr->second;
	else if(bInsert) {
		parr= new CBondList;
		m_map.insert(std::pair<std::string,CBondList*>(sGroup,parr));
	}
	return parr;
}

bool CBondDict::GetBondDict(const char* sGroup, const char* sCode, BondDict &stDict)
{
	memset(&stDict,0,sizeof(BondDict));

	if(sGroup == NULL || sCode == NULL ) return false;
	if(strlen(sGroup) == 0 || strlen(sCode) == 0 ) return false;

	std::lock_guard<std::mutex> locker(m_mutex);
	CBondList *parr = NULL;
	parr=GetBondArrByGroup(sGroup);
	if(parr)
	{
		std::string strMapKey = std::string(sGroup) + "." + std::string(sCode);
		std::map<std::string, BondDict> ::iterator itr = parr->m_list.find(strMapKey);
		if(itr!= parr->m_list.end())
		{
			stDict = itr->second;
			return true;
		}
	}
	return false;
}

bool CBondDict::Clear( )
{
	std::lock_guard<std::mutex> locker(m_mutex);

	std::map<std::string, CBondList*> ::iterator itr = m_map.begin();
	for(itr=m_map.begin();itr!=m_map.end();itr++)
	{
		CBondList *parr = itr->second;
		if(parr)delete parr;
		parr = NULL;
	}
	m_map.clear();
	return true;
}


void CBondDict::DumpStatus(int mode)const
{

}